  package bd403.UIComponents;

import java.util.ArrayList;
import java.util.Iterator;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import bd403.Backend.Drink;
import bd403.Backend.DrinkStorage;
import bd403.namespace.BDActivity;
import bd403.namespace.R;
import bd403.utils.DrinkAdapter;
import bd403.utils.KeyboardSetup;

/* UI and functionality for the Search page of the BrewDawg application. On this page, users can
 * search for a drink via scrollable list or search box.
 * Main author: Mike
 */

public class SearchActiv extends ListActivity {
	
	private static final String SHOWALL = "showAll";
	private static final String SEARCH = "SearchDrinks";
	private ArrayList<Drink> m_orders;
	private DrinkAdapter m_adapter;
	private String task;
	
	/* Initializes the Search Activity UI */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setup();
	}
	
	/* Setup the XML layout, UI of the search page, and display drinks to the user.
	 */
	private void setup() {
		setContentView(R.layout.searchpage);
		m_orders = null;
		
		initializeSearchPage();
		setupSearchButton();
		
		/* Show all drinks initially */
		task = getString(R.string.message_loading);
		bdSyncTask serverConnect = new bdSyncTask();
		serverConnect.execute(SHOWALL);
	}
	
	/* Updates the list of drinks to display on the search results list.
	 */
	private void viewDrinkList(Iterator<Drink> drinks) {
		m_orders.clear();
		if (drinks != null) {
			while (drinks.hasNext()) {
				m_orders.add(drinks.next());
			}
		}
	}
	
	/* Set up the UI of the Search page and search results list.
	 */
	private void initializeSearchPage() {
		m_orders = new ArrayList<Drink>();
		this.m_adapter = new DrinkAdapter(this, R.layout.drinkitem, m_orders);
		setListAdapter(this.m_adapter);
		setViewSettings();
		setupAutoComplete();
	}
	
	/* Set up the Auto-complete feature of Search.
	 */
	private void setupAutoComplete() {
		DrinkStorage ds = BDActivity.getStorage();
		AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.searchenter);
	    textView.setAdapter(new ArrayAdapter<String>(this, R.layout.listitem, ds.getDrinkNames()));
	}
	
	/* Sets up the soft keyboard to minimize on a 'Return' key click, and setup listener
	 * for a 'Search' button click.
	 */
	private void setupSearchButton() {
		final EditText searchText = (EditText) findViewById(R.id.searchenter);

		KeyboardSetup ks = KeyboardSetup.getInstance(this);
		ks.setupKeyboard(searchText);

		/* Register a listener for the search submit button */
		Button submit = (Button) findViewById(R.id.searchsubmit);
		submit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				task = getString(R.string.message_searching);
				bdSyncTask serverConnect = new bdSyncTask();
				serverConnect.execute(SEARCH);
			}
		});
	}
	
	/* Private helper class used to execute an asynchronous request to the server.
	 * Runs in the background while the main UI thread runs in the foreground.
	 */
	private class bdSyncTask extends AsyncTask<String, Void, Void> {
		private ProgressDialog dialog; // dialog to display while connecting to the server

		/* Setup inpStream and parameters needed to execute the task prior to
		 * doing the work.
		 */
		@Override
		protected void onPreExecute() {
			dialog = ProgressDialog.show(SearchActiv.this, "", task, true, false);
		}

		/* Task this thread will run in the background when the .execute()
		 * method is invoked.
		 */
		@Override
		protected Void doInBackground(String... param) {
			DrinkStorage ds = BDActivity.getStorage();
			if (param[0].equals(SHOWALL)) {
				viewDrinkList(ds.allDrinks());
			} else if (param[0].equals(SEARCH)) {
				final EditText searchText = (EditText) findViewById(R.id.searchenter);
				viewDrinkList(ds.findMatchingDrinks(searchText.getText().toString()));
			}
			return null;
		}

		/* Executed after doInBackground has completed to compute final results.
		 */
		protected void onPostExecute(Void arg1) {
			// Dismiss 'Search' dialog
			dialog.dismiss();
			m_adapter.notifyDataSetChanged();
		}
	}

	/* Sets up the background colors and keyboard functionality for the Search Page.
	 */
	private void setViewSettings() {
		ListView lv = getListView();
		lv.setBackgroundColor(Color.BLACK); 
		lv.setCacheColorHint(Color.BLACK);
		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				onClick(view, position, id);
			}	
		});
	}
	
	/* Sets up the function for the on-click of a specific drink.
	 */
    protected void onClick(View v, int position, long id) {
        Intent i = new Intent(this, DrinkViewActiv.class);
        Drink d = m_adapter.getItem(position);
        
        // Data bind drink d to pass it to a new Activity
        DrinkStorage ds = BDActivity.getStorage();
        ds.setCurrentDrink(d);
        startActivity(i);
    }
    
    /* Refreshes the Search page when a user comes back to it after adding a drink.
	 */
    protected void onResume() {
    	super.onResume();
		setup();
    }
}